package com.study.xml.junit;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.study.xml.utils.JAXPDOMParseUtils;

/**
* @Name: JAXPDOMParseTest
* @Description: JAXP-DOM解析测试类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-26 上午9:23:09 
* @Version: V1.0
 */
public class JAXPDOMParseTest {
	
	@Test
	public void findElement() throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
		DocumentBuilder builder = factory.newDocumentBuilder() ;
		String uri = "src/books.xml" ;
		Document document = builder.parse(uri) ;
		String xmlVersion = document.getXmlVersion() ;
		String xmlEncoding = document.getXmlEncoding() ;
		boolean xmlStandalone = document.getXmlStandalone() ;
		System.out.println("xmlVersion : " + xmlVersion);
		System.out.println("xmlEncoding : " + xmlEncoding);
		System.out.println("xmlStandalone : " + xmlStandalone);
		NodeList nodeList = document.getElementsByTagName("售价") ;
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node item = nodeList.item(i) ;
			String textContent = item.getTextContent() ;
			System.out.println(textContent);
		}
	}
	
	@Test
	public void findElementByJAXPDOMParseUtils() {
		String uri = "src/books.xml" ;
		Document document = JAXPDOMParseUtils.getDocument(uri) ;
		NodeList nodeList = document.getElementsByTagName("作者") ;
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i) ;
			String textContent = node.getTextContent() ;
			System.out.println(textContent);
		}
	}
	
	@Test
	public void insertElement() {
		String uri = "src/books.xml" ;
		Document document = JAXPDOMParseUtils.getDocument(uri) ;
		//新建元素
		String tagName = "批发价" ;
		Element element = document.createElement(tagName) ;
		String nodeValue = "800" ;
		element.setTextContent(nodeValue) ;
		Element node = (Element) document.getElementsByTagName("书").item(2) ;
		//建立关系
		node.appendChild(element) ;
		//写回到xml
		JAXPDOMParseUtils.writeDOM2XML(document, uri) ;
	}

}




